import datetime
import re
import time

from dateutil.parser import parse


def datetime_verify(date_):
    """判断是否是一个有效的日期字符串"""
    if not isinstance(date_, str):
        return False
    units = re.findall(r"\d{4}(.)\d{1,2}(.)\d{1,2}(.?)", date_)
    if units:
        year_unit, month_unit, day_unit = units[0]
        try:
            time.strptime(date_, "%Y" + year_unit + "%m" + month_unit + "%d" + day_unit)
            return True
        except ValueError:
            return False
    return False


class DateMixIn(object):
    @staticmethod
    def process_date(date):  # 从满足日期格式的文本中提取出标准格式   20xx-xx-xx
        if not (date or isinstance(date, str)):
            return None
        reg = re.findall(r'[年\-](.*?)[月\-](.*?)[日号]', date)
        if reg:
            year = re.findall(r'(.*)[年\-]', date)[0]
            replace_dict = {
                '0': ['零', '〇', '○'],
                '2': ['二十', '贰拾', '二', '贰'],
                '3': ['三十', '叁拾', '三', '叁'],
                '4': ['四', '肆'],
                '5': ['五', '伍'],
                '6': ['六', '陆'],
                '7': ['七', '柒'],
                '8': ['八', '捌'],
                '9': ['九', '玖'],
                '1': ['十', '一', '壹'],
            }
            mon = reg[0][0]
            day = reg[0][1]
            if mon[-1] == '十':
                mon = mon.replace('二十', '20').replace('三十', '30').replace('十', '10')
            if day[-1] == '十':
                day = day.replace('二十', '20').replace('三十', '30').replace('十', '10')
            date = f'{year}-{mon}-{day}'
            for k, v in replace_dict.items():
                for i in v:
                    date = date.replace(i, k)
        num_date = re.findall(r'(20\d\d)\D+(\d{1,2})\D+(\d{1,2})', str(date))
        if num_date:
            year, month, date = num_date[0]
            valid_date = "%d-%02d-%02d" % (
                int(year), int(month), int(date))  # 一是格式标准，二是方便排序（存mongo时，存的是字符类型，对字符排序是逐个字符ascii码比较 ，用这种方式存储能起到排序的功能）
            if datetime_verify(valid_date):
                return valid_date
        return None

    @staticmethod
    def process_lack_date(date):
        if not (date and isinstance(date, str)):
            return '1970-01-01'
        default_date = datetime.datetime.strptime('1970-01-01', '%Y-%m-%d')
        date = re.sub(r'[^\d:：日]', '-', date).strip('-').replace('日', ' ')
        try:
            date = parse(date, default=default_date)
        except:
            return '1970-01-01'
        else:
            return date.strftime('%Y-%m-%d')
